﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ops.Mpc.ExampleApplication.Web.BusinessObjects.Filters;

namespace Ops.Mpc.ExampleApplication.Web.BusinessObjects
{
    public class BusinessObjectManager
    {
        #region Fields & Properties
        private static readonly List<Person> _persons = new List<Person>();
        private static readonly object _lock = new object();
        #endregion

        #region Constructors
        static BusinessObjectManager()
        {
            lock (_lock)
            {
                for (int count = 0; count < 200; count++)
                    _persons.Add(new Person() { PersonId = count, FirstName = PersonNamesFactory.CreateFirstName(), LastName = PersonNamesFactory.CreateSurname() });
            }

        }
        #endregion

        #region Methods
        public Person CreatePerson(string firstName, string lastName)
        {
            lock (_lock)
            {
                Person person = new Person() { PersonId = _persons.Count , FirstName = firstName, LastName = lastName };
                _persons.Add(person);
                return person;
            }
        }

        public Person[] GetPersons(Pager pager)
        {
            lock (_lock)
            {
                IQueryable<Person> query = _persons.AsQueryable<Person>();
                if (pager.Filters != null)
                {
                    foreach (Filter filter in pager.Filters)
                        if (!(filter is SortFilter))
                        {
                            query = filter.Apply<Person>(query);
                        }

                    foreach (Filter filter in pager.Filters)
                        if (filter is SortFilter)
                        {
                            query = filter.Apply<Person>(query);
                        }
                }

                return query.Skip(pager.PageSize * pager.CurrentPageIndex).Take(pager.PageSize).ToArray();
            }
        }

        public Pager GetPersons(Filter[] filters)
        {
            lock (_lock)
            {
                IQueryable<Person> query = _persons.AsQueryable<Person>();

                if (filters != null)
                    foreach (Filter filter in filters)
                        if (!(filter is SortFilter))
                            query = filter.Apply<Person>(query);


                return new Pager() { Count = query.Count(), Filters = filters };
            }
        }

        #endregion





 
    }
}